package com.heima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.heima.common.PageResult;
import com.heima.mapper.ShopCategoryMapper;
import com.heima.pojo.SkuClass;
import com.heima.pojo.dto.PageDto;
import com.heima.pojo.dto.SkuClassDto;
import com.heima.pojo.vo.SkuClassVo;
import com.heima.service.ShopCategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
@Transactional
public class ShopCategoryServiceImpl implements ShopCategoryService {

    @Autowired
    private ShopCategoryMapper shopCategoryMapper;

    /**
     * 新增
     * @return
     */
    @Override
    public Object save(SkuClassDto shopDto) {
        SkuClass skuClass = new SkuClass();
        BeanUtils.copyProperties(shopDto,skuClass);
        Integer insert = shopCategoryMapper.insert(skuClass);
        return insert;
    }

    /**
     * 分页查询
     * @param pageDto
     * @return
     */
    @Override
    public PageResult<SkuClass> search(PageDto pageDto) {
        PageHelper.startPage(pageDto.getPageIndex(), pageDto.getPageSize());
        Page<SkuClass> list = shopCategoryMapper.search(pageDto);
        // 计算总页数
        int totalPage = (int) Math.ceil((double) list.getTotal() / pageDto.getPageSize());
        return new PageResult<>(
                pageDto.getPageIndex(),
                pageDto.getPageSize(),
                totalPage,
                list.getTotal(),
                list.getResult()
        );
    }

    /**
     * 根据id查询
     * @param classId
     * @return
     */
    @Override
    public SkuClassVo getById(String classId) {
        SkuClassVo skuClassVo = shopCategoryMapper.getById(classId);
        return skuClassVo;
    }

    /**
     * 修改商品分类信息
     * @param skuClassDto
     * @return
     */
    @Override
    public Boolean modify(SkuClassDto skuClassDto) {
        SkuClass skuClass = new SkuClass();
        BeanUtils.copyProperties(skuClassDto,skuClass);
        Integer math = shopCategoryMapper.modify(skuClass);
        return math > 0;
    }

    /**
     * 删除
     * @param classId
     */
    @Override
    public void deleteById(String classId) {
        // 判断该商品分类下面是否绑定了商品，如果绑定了商品则不允许删除
        Integer count = shopCategoryMapper.countByClassId(classId);
        if (count > 0) {
            throw new RuntimeException("该商品分类下有商品，不允许删除");
        }
        if (classId != null) {
            shopCategoryMapper.deleteById(classId);
        }
    }


}
